//
//  TaskTest2View.swift
//  MakeMoney
//
//  Created by Fan ZhiQiang on 2025/8/19.
//

import SwiftUI

struct TaskTest2View: View {
    @State private var results: [String] = []
    var body: some View {
        VStack {
            ForEach(results, id: \.self) { result in
                Text(result)
            }
        }.onAppear {
            Task {
                //在这里 async let 开启并行任务
                print("开始执行3")
                async let data1 = getData(id: 3)
                print("开始执行2")
                async let data2 = getData(id: 2)
                print("开始执行1")
                async let _ = getData(id: 1)
                print("开始执行4")
                async let data4: () = getTestData(id: 4)
                let result1 = await data1
                let result2 = await data2
                
                await data4
                print("等待结束")
                results = [result1, result2]
            }
        }
    }
    
    func getData(id: Int) async -> String {
        print("getData -- \(id)")
        try? await Task.sleep(nanoseconds: UInt64(id) * 1_000_000_000)
        return "Data id \(id)"
    }
    
    func getTestData(id: Int) async {
        print("getTestData -- \(id)")
        try? await Task.sleep(nanoseconds: UInt64(id) * 1_000_000_000)
    }
}

#Preview {
    TaskTest2View()
}
